import 'package:flutter/material.dart';
import 'package:x3_base_core/base_utils/base_utils.dart';
import 'package:x3_component_core/x3_component_core.dart';

class BaseInputDialogComponent extends StatefulWidget {
  /// 标题信息
  final String title;

  /// 初始值
  final String initValue;

  /// 提示文本
  final String notes;

  /// 键盘类型
  final TextInputType keyboardType;

  /// 是否为必填
  final bool isRequired;

  /// 输入完成之后 点击事件
  final void Function(String value) onInputOKPress;

  /// 允许输入的行数
  final bool isMultipleLines;

  BaseInputDialogComponent({
    Key key,
    @required this.onInputOKPress,
    this.title,
    this.initValue,
    this.notes = '请输入',
    this.isMultipleLines = false,
    this.keyboardType = TextInputType.text,
    this.isRequired = false,
  }) : super(key: key);

  @override
  _BaseInputDialogComponentState createState() => _BaseInputDialogComponentState();
}

class _BaseInputDialogComponentState extends State<BaseInputDialogComponent> {
  String _value;

  @override
  void initState() {
    _value = widget.initValue == null ? '' : widget.initValue;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BaseDialogComponent(
      onOKPress: (widget.isRequired == true && _value.isEmpty) ? null : () => {if (widget.onInputOKPress != null) widget.onInputOKPress(_value)},
      title: widget.title,
      contentWidget: _buildContentWidget(),
    );
  }

  Widget _buildContentWidget() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 5.0),
      margin: const EdgeInsets.only(bottom: 12.0),
      decoration: BoxDecoration(border: Border.all(color: Color(0xFFF3F3F3)), borderRadius: BorderRadius.circular(2)),
      child: BaseTextField(
        maxHeight: widget.isMultipleLines ? 80 : 32,
        keyboardType: widget.keyboardType,
        textInputAction: TextInputAction.done,
        value: widget.initValue,
        maxLines: widget.isMultipleLines ? 5 : 1,
        hintText: widget.notes,
        onChanged: _onChanged,
        autoFocus: true,
        onSubmitted: _onSubmit,
      ),
    );
  }

  void _onChanged(String value) {
    setState(() {
      _value = value;
    });
  }

  void _onSubmit(String value) {
    if (widget.isRequired == true && value.isEmpty) {
      BaseUtils.showToast('请输入信息');
      return;
    }
    if (widget.onInputOKPress != null) {
      widget.onInputOKPress(value);
    }
  }
}
